package com.zhanglijie.base.volatileLearn;

import java.util.concurrent.TimeUnit;

import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;

/**
 * @author zhanglijie
 * @version 1.0
 * @since 1.1.0 2022/5/17 0017 23:06
 */
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class TlabTestNoShare {
    public static void main(String[] args) throws RunnerException {
        Options build = new OptionsBuilder().include(TlabTestNoShare.class.getSimpleName())
            .forks(1)//一般fork个子进程来执行避免干扰
            .warmupIterations(5)//先预热五次 排除前几次的概率时间
            .measurementIterations(5)//正式执行五次
            .threads(4)
            .build();
        new Runner(build).run();
    }
    public static class MyObject{
        volatile int  myValue;

    }

    /**
     * 1.share线程组共享创建
     * 2.每个线程各自创建
     */

    @State(Scope.Thread)
    public static class MyCount{
        MyObject[] myObjects = new MyObject[2];
        public MyCount(){
            myObjects[0] = new MyObject();
            myObjects[1] = new MyObject();
        }
    }
    @Benchmark
    public void testA(MyCount myCount){
        myCount.myObjects[0].myValue++;
    }
    @Benchmark
    public void testB(MyCount myCount){
        myCount.myObjects[1].myValue++;
    }
}
